//
//  AppDataConfigure.swift
//  ManBetX
//
//  Created by Cocoa on 2020/4/15.
//  Copyright © 2020 Fullen. All rights reserved.
//

import UIKit
import Eagleeyes.DevicePrint

/**
 * 配置一些全局数据、文件
 */
class AppDataConfigure: NSObject {
    
//MARK:-- 鹰眼接口   requestEagleeyes- 外部调用
    //调用鹰眼接口
    class func requestEagleeyes(){
        var number = UserDefaults.standard.integer(forKey: DefaultKey.EAGLEEYES_NUMBER)
        if number >= 3 {
            number = 1
        }else{
            number += 1
        }
        print("当前鹰眼-\(number)")
        UserDefaults.standard.set(number, forKey: DefaultKey.EAGLEEYES_NUMBER)
        let blackbox :String = DevicePrint.getBlackBox() ?? ""
        NetWorkRequest(API.requsetEagleeyes2(url: "94a0356", blackBox: blackbox, type: "login", dno: "",ipaddress:""), completion: { (responseData,statusCode,strData) -> (Void) in
                print("登录后鹰眼返回:",responseData,statusCode,strData)
            }, failed: { (faildInfo,reCode,msg) -> (Void) in
                print("登录后鹰眼返回:",faildInfo,reCode,msg)
            }) { () -> (Void) in
                print("登录后鹰眼返回错误")
            }
        }
    
//MARK:-- GameJson 策略  configureGameJson、getGameJsonData- 外部调用
    /**
     * 获取GameJson 策略
     * 1、本地内置文件 [每次发包更新]
     * 2、本地缓存文件 [每次通过网络请求文件更新]
     * 3、网络请求文件 [每次进入APP时获取 - 更新本地缓存文件]
     *
     * 进入APP时 - 先取本地缓存文件、如果没有取本地内置文件。
     */
    
    //本地已缓存GameJson文件、本地内置GameJson文件 - 刷新本地配置
    class func configureGameJson(afterBlock: @escaping () -> Void){
        
        DispatchQueue.main.async {
            let cacheGameJson = UserDefaults.standard.dictionary(forKey: DefaultKey.CACHE_GAME_JSON)
            if cacheGameJson != nil {
                // 配置 -- 本地已缓存GameJson文件
                self.setGameData(gameInfoDic: cacheGameJson!,afterBlock:afterBlock)
                
            }else {
                // 配置 -- 本地内置GameJson文件
                do{
                    let path = Bundle.main.path(forResource: "DefaultGameJson", ofType:"txt")
                    let content = try String(contentsOfFile: path!)
                    let jsonData = content.data(using: String.Encoding.utf8, allowLossyConversion: false) ?? Data()
                    let gameInfoArray = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [String: Any]
                    print("本地内置gameJson已经配置")
                    //print("同步获取gameJson: \(gameInfoArray)")
                    self.setGameData(gameInfoDic: gameInfoArray!,afterBlock:afterBlock)
                    
                }catch{
                    print("本地内置gameJson配置出错")
                }
            }
        }
    }
    
    //网络请求GameJson - 请求成功后本地缓存（然后刷新本地配置？可商讨要不要刷新本地配置）
   class func getGameJsonData(){
        let randomNumber:Int = Int(arc4random() % 100) + 1
        RequestHelper.get(GlobalInfo.resDomain, atPath: "\(GlobalInfo.getGameJson)?random=\(randomNumber)", withCompletion: { data in
            let gameInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            // 本地缓存gameJson
            UserDefaults.standard.set(gameInfoArray, forKey: DefaultKey.CACHE_GAME_JSON)

//             print("已经异步获取gameJson: \(gameInfoArray)")
//             DispatchQueue.main.async {
//                self.setGameData(gameInfoDic: gameInfoArray)
//            }
        }, withError: { error in
        })
    }
    
    // GameJson文件 - 本地配置
   class func setGameData(gameInfoDic:[String:Any],afterBlock: @escaping () -> Void){
        GlobalInfo.gameInfoData = gameInfoDic
        
        let platforms = gameInfoDic["platforms"] as! [[String:Any]]
        GlobalInfo.platformInfoData = platforms
    
        
        let recommendGame = gameInfoDic["recommendGame"] as? [[String:Any]]
        GlobalInfo.recommendGame = recommendGame
    
//        let helpers = gameInfoDic["helper"] as! [[String:Any]]
        let activitycategory = gameInfoDic["activitycategory"] as! [[String:Any]]
        GlobalInfo.helperList = gameInfoDic["helper_List"] as? [[String:Any]]
        
        var activitys : [[String:Any]] = []
        for temp in activitycategory{
            var data : [String:Any] = [:]
            data["actypename"] = temp["aname"]
            data["actypesort"] = 0
            data["actypeid"]  = temp["atype"]
            activitys.append(data)
        }

        GlobalInfo.sponsorUrl = gameInfoDic["tabUrl"] as? String ?? ""
        GlobalInfo.activitycategoryData = activitys
        //自助客服是否可以用
        GlobalInfo.isCsAuto=gameInfoDic["is_cs_auto"] as? Bool
        //主账户是否使用H5页面
        GlobalInfo.isPlatformMainhtml = gameInfoDic["is_platform_mainH5"] as? Bool
        //是否使用原生取款
         GlobalInfo.isWithdrawNative = gameInfoDic["isWithdrawNative"] as? Bool ?? false
        //客服弹窗是否显示拨打客服号码
        let phone =  gameInfoDic["is_callback_phone"] as? NSNumber
        let phoneStr = phone?.stringValue
        GlobalInfo.isCallbackPhone = phoneStr
        //是否缓存首页游戏平台图标
        GlobalInfo.isPlatformIconcache = gameInfoDic["is_platform_iconcache"] as? Bool
        //广告图
        GlobalInfo.adUrl = gameInfoDic["ad_url"] as? String
        //安全中心地址
        GlobalInfo.safeUrl = gameInfoDic["safe_url"] as? String
        //收藏我们地址
        GlobalInfo.collectUsUrl = gameInfoDic["collectUsUrl"] as? String
        //客服地址
        GlobalInfo.serviceIurl=gameInfoDic["service_iurl"] as? String
        GlobalInfo.serviceIurlsec=gameInfoDic["service_iurl_sec"] as? String
        GlobalInfo.codeTimeInterval = gameInfoDic["codeTimeInterval"] as? Int ?? 120
        //自助客服的地址
        GlobalInfo.csDownClient = gameInfoDic["cs_down_client"] as? String
        GlobalInfo.serviceSelfIurl=gameInfoDic["service_self_iurl"] as? String
        //存款方式列表
        let paymentlist = gameInfoDic["paymentlist"] as? [[String:Any]]
        GlobalInfo.paymentlist = paymentlist
        //存款模式列表 3.0
        let depoistModelList =  gameInfoDic["depoistModelList"] as? [[String:Any]]
        GlobalInfo.depoistModelList = depoistModelList
        //存款支付通道列表
        let bankList = gameInfoDic["bank_list"] as? [[String:Any]]
        GlobalInfo.bankList = bankList
        //ATM通道
        GlobalInfo.companyATM = gameInfoDic["companyATM"] as? [String:String]
        //存款按钮金额
        GlobalInfo.moneyButton = gameInfoDic["moneyButton"] as? [String]
        //活动id列表
        GlobalInfo.activityIds = gameInfoDic["activityIds"] as? [String]
        let bankImages = gameInfoDic["bank_images_code"] as? [[String:Any]]
        //app图标类型
        GlobalInfo.appIconType = gameInfoDic["appIconType"] as? Int ?? 0
        self.changeAppicon()
        GlobalInfo.bankImages = bankImages
        /**** Game Info Data ****/
        var gameInfoData = gameInfoDic
        gameInfoData.removeValue(forKey: "platforms")
       let _ = GlobalInfo.isMaintain()
    
        afterBlock()
    }
    
    //更换app图标类型
    class func changeAppicon() -> Void {
        if #available(iOS 10.3, *) {
            DispatchQueue.main.async {
                if !UIApplication.shared.supportsAlternateIcons {
                    return
                }
                let random = GlobalInfo.appIconType
                // let iPad = (UI_USER_INTERFACE_IDIOM() == .pad)
                var iconName: String? // nil表示使用App原来的图标
                if random == 0{ //默认
                    iconName = nil
                }else if random == 1 { // 新春节
                    //iconName = iPad ? "AppAlternateIconiPad" : "AppAlternateIcon"
                    iconName = "xinchun"
                } else if random == 2 { // 万博节
                    iconName = "wanbo"
                }else if random == 3 { // 端午节
                    iconName = "duanwu"
                }else if random == 4{ //中秋节
                    iconName = "zhongqiu"
                }else if random == 5{ //国庆节
                    iconName = "guoqing"
                }else if random == 6{ //双11节
                    iconName = "shuang11"
                }else if random == 7{ //双12节
                    iconName = "shuang12"
                }else if random == 8{ //双旦节
                    iconName = "shuangdan"
                }
                if UIApplication.shared.alternateIconName == iconName {
                    // App图标已是当前选中的图标，无需更换
                    return
                }
                UIApplication.shared.setAlternateIconName(iconName, completionHandler: nil)
            }
        }
    }
    
//MARK:-- getDoMainIp 轮询IP getDoMainIp- 外部调用
    
    class func getDoMainIp(succeedBlock: @escaping() -> Void){
        UserDefaults.standard.set(GlobalInfo
            .apiDomain, forKey: DefaultKey.USER_DOMAIN)
        succeedBlock()
        
//        var index = 0
        
//        if(isTest){
//            kMainIpArray = Array<String>.init()
//            kMainIpArray.append(GlobalInfo.doMainTest)
//        }
//        if(index>(kMainIpArray.count-1)){
//            return
//        }
//        UserDefaults.standard.set(false, forKey: DefaultKey.IS_IP_STATUS)
//        UserDefaults.standard.set(kMainIpArray[index], forKey: DefaultKey.IP_DOMAIN)
//        UserDefaults.standard.set(kMainIpArray[index].replacingOccurrences(of: "https://", with: ""), forKey: DefaultKey.USER_DOMAIN)
//        RequestHelper.get(atPath: "/service/vpkey", withCompletion: { (data) in
//            let dic = try JSONSerialization.jsonObject(with: data, options: []) as? [String: String]
////            print("isIpStatis=======>\(dataArray)")
//            if dic?.keys.contains("modulus") ?? false && dic?.keys.contains("exponent") ?? false{
//                let isIpStatus = UserDefaults.standard.bool(forKey: DefaultKey.IS_IP_STATUS)
//                if isIpStatus == false{
//                    print("可用域名")
//                    DispatchQueue.main.async {
//                        UserDefaults.standard.set(true, forKey: DefaultKey.IS_IP_STATUS)
//                        UserDefaults.standard.set(kMainIpArray[index], forKey: DefaultKey.IP_DOMAIN)
//                        UserDefaults.standard.set(kMainIpArray[index].replacingOccurrences(of: "https://", with: ""), forKey: DefaultKey.USER_DOMAIN)
//                        UserDefaults.standard.set(dic?["modulus"], forKey: DefaultKey.MODULUS)
//                        UserDefaults.standard.set(dic?["exponent"], forKey: DefaultKey.EXPONENT)
//
//                        succeedBlock(dic)
//                    }
//                }
//            }
//        }) { (error) in
//            index += 1
//            self.getDoMainIp { (dic) in}
//        }
    }
    
//MARK:-- signkey  getSignKey- 外部调用
    //获取signkey
    class func getSignKey(succeedBlock: @escaping () -> Void,failedBlock: @escaping () -> Void){
        UserDefaults.standard.set(false, forKey: DefaultKey.IS_SIGNKEY_STATUS)
        NetWorkRequest(API.getSignKey(url: "cdb60a1"), completion: { (responseData, statusCode, strData) -> (Void) in
            DispatchQueue.main.async {
                UserDefaults.standard.set(responseData["response"].string ?? "" , forKey: DefaultKey.SIGNKEY)
                UserDefaults.standard.set(true, forKey: DefaultKey.IS_SIGNKEY_STATUS)
                succeedBlock()
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            failedBlock()
            print("重大问题 -- 获取 SignKey 失败")
        }) { () -> (Void) in
            failedBlock()
            print("重大问题 -- 获取 SignKey 失败")
        }
    }
    
//MARK:-- newCheckLocation2 - 检查IP看是否需要展示禁止访问页 newCheckLocation2- 外部调用
    class func newCheckLocation2(fobiddenBlock: @escaping () -> Void){
        
        let whiteListIp = [
            "123.176.102.158",
            "106.187.42.114",
            "106.185.30.139",
            "106.185.48.23",
            "154.209.20.218",
            "210.245.206.147",
            "182.239.82.117"
        ]
        
        NetWorkRequest(API.getGeo(url: "62bcad1"), completion: { (responseData,statusCode,strData) -> (Void) in
            let dict =  responseData["data"].dictionaryValue
            let responseDict = dict["response"]?.dictionaryObject
            
            if responseDict != nil {
                if let ip = responseDict?["ip"] as? String{
                     ipAddress = ip
                    if !whiteListIp.contains(ip){
                        DispatchQueue.main.async {
                            let country = responseDict?["country"] as? String
                            let banded = ["KH","PH","MY","LA","TW","HK","MO","US","SG"]
                            //如果country是菲律宾,或者是香港，或者不是europe数组里其中一个则显示ip限制页面
                            if country != nil{
                                if banded.contains(country!){
                                    fobiddenBlock()
                                }
                            }
                        }
                    }
                }else {
                    //ip为空
                }
            }else{
                //responseDict为空
             }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in }) { () -> (Void) in }
    }
     
    /*
     * https://api.ydahu.com/api/v1/appchannel
     * 获取域名接口配置 - 同时也是版本更新
     */
    
    class func fetchAppchannel(succeedBlock: @escaping(_ dataDic: [String:Any]) -> Void) {
        
//        https://api.ydahu.com/api/download/config.json gameJson下载地址
        
        let tagFlag = GlobalInfo.tagFlag
        // platform：1 - 标识 iOS平台
        NetWorkRequest(API.appchannel(tag:tagFlag, platform: 1), completion: { (responseData, statusCode, messgeStr) -> (Void) in
            if responseData["data"].dictionaryObject != nil {
                let dict = responseData["data"].dictionaryObject! as [String: Any]
                GlobalInfo.appChannelDic = dict
                succeedBlock(dict)
            }
        }) { (faildInfo,reCode,msg) -> (Void) in
            print("11")
        }
    }
    
    /*
     // 1.0域名
     host
     // 2.0域名
     host2
     // 资源 - gameJson - 注意这里是全部链接？
     host3
     // 渠道名称
     tag_name
     // 更新状态
     let statusType = dataDic.object(forKey: "status_type") as? Int ?? 0
     // 当前版本
     let currentVersion = dataDic.object(forKey: "current_version") as? String ?? ""
     // 全量版本 - 需要重新跳转网页下载
     let full_version = dataDic.object(forKey: "full_version") as? String ?? ""
     // 增量版本 - 热更
     let patch_version = dataDic.object(forKey: "patch_version") as? String ?? ""
     //下载地址
     download_url
     //全量地址
     full_download_url
     //增量地址
     patch_path
     
     // 状态名称
     status_name
     //更新说明
     notes
     // 平台
     platform
     // 渠道标识
     tag
     */
    
    // 检测是否需要版本更新 -- 强制更新
    class func isNeedUpdateVersion() -> Bool{
    
        // 1、给出当前APP的版本
        // 2、比较用户APP的版本与全量版本，给出bool值
        if GlobalInfo.appChannelDic == nil {
            return false
        }
        
        let dataDic: [String: Any] = GlobalInfo.appChannelDic!
           
        // 更新状态
        let statusType = dataDic["status_type"] as? Int ?? 0
        // 全量版本 - 需要重新跳转网页下载
        let fullVersion = dataDic["full_version"] as? String ?? ""
        
        let isNewVersion =  AppDataConfigure.compareUerVersionWithFullVersion(fullVersion: fullVersion)

        if isNewVersion == true {
            // 有新版本，记录版本弹框 字段重置
            UserDefaults.standard.set(false, forKey: DefaultKey.APP_SHOW_VERISON_INFO_YET)
            
            //有强制新 -- 判断后台给的更新状态
            // 1 最新版本
            // 2 提示更新
            // 3 强制更新
            // 4 不提示更新
            // 后面写热更的时候，会替换成枚举，现在偷个懒，先写死
            if statusType == 3 {
                return true
            }
        }
 
//            //全量地址
//            full_download_url
//
//
//            // 状态名称
//            status_name
//            //更新说明
//            notes
        
        return false
    }
    
    // 用户版本与全量版本比较 - true 有新版本；- false 无新版本
    class func compareUerVersionWithFullVersion(fullVersion: String) ->Bool {
        let infoDictionary = Bundle.main.infoDictionary as NSDictionary?
        let app_Version = infoDictionary?.object(forKey: "CFBundleShortVersionString") as! String
        // 保存用户更新前的版本号
//        UserDefaults.standard.set(app_Version, forKey: DefaultKey.APP_CURRENT_VERISON)
        
        let uerVersionArray = app_Version.components(separatedBy: ".") as NSArray
        
        let fullVersionArray = fullVersion.components(separatedBy: ".") as NSArray
        
        if uerVersionArray.count > 0,fullVersionArray.count > 0 {
            let minCount = min(uerVersionArray.count, fullVersionArray.count)
            
            for index in 0..<minCount {
                let userSring: String = uerVersionArray.object(at:index) as! String
                let fullSring: String = fullVersionArray.object(at:index) as! String
                let uerInt = Int(userSring)!
                let fullInt = Int(fullSring)!
                if uerInt < fullInt {
                    let infoDictionary = Bundle.main.infoDictionary as NSDictionary?
                    let app_Version = infoDictionary?.object(forKey: "CFBundleShortVersionString") as! String
                    // 保存用户更新前的版本号
                    UserDefaults.standard.set(app_Version, forKey: DefaultKey.APP_CURRENT_VERISON)
                    
                    return true
                }else if uerInt > fullInt {
                    return false
                }
                continue
            }
        }
        return false
    }
    
    /*
     * 检测是否需要展示新版本信息
     * 注意：只有当不需要更新的时候，才能进行这一步。避免更新弹框和信息弹框同时出现
     */
    class func isNeedShowVersionInfo() -> Bool {
        
        // 获取用户是否已经弹出过一次提示框
        let appShowVersionYet = UserDefaults.standard.bool(forKey: DefaultKey.APP_SHOW_VERISON_INFO_YET)
        // 获取用户更新前的版本号
        let oldVersion = UserDefaults.standard.string(forKey: DefaultKey.APP_CURRENT_VERISON)
        if oldVersion != nil {
            if appShowVersionYet == false , GlobalInfo.appChannelDic != nil{
                
                let infoDictionary = Bundle.main.infoDictionary as NSDictionary?
                let app_Version = infoDictionary?.object(forKey: "CFBundleShortVersionString") as! String
                
                if oldVersion != app_Version {
                    return true
                }
            }
        }
        return false
    }
}
